package com.jsj.isdt.servlet;

import com.alibaba.fastjson.JSON;
import com.jsj.isdt.entity.Book;
import com.jsj.isdt.entity.Supplier;
import com.jsj.isdt.utils.DBUtils;
import com.jsj.isdt.utils.ResultData;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.List;

public class ServletBo extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        String action = req.getParameter("action") == null ? "" : req.getParameter("action");
        switch (action) {
            case "getdglist":
                getDglist(req, resp);
                break;
            case "add":
                Add(req, resp);
                break;
            case "exists":
                Exists(req, resp);
                break;
            case "delete":
                Delete(req, resp);
                break;
            case "getone":
                getOne(req, resp);
                break;
            case "update":
                update(req, resp);
                break;
            case "reg":
                Reg(req, resp);
            default:
                break;
        }
    }


        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

            doGet(req,resp);
        }
    private  void  getDglist (HttpServletRequest req, HttpServletResponse resp)  {
        try {
            int  pageIndex = req.getParameter("page") ==null? 1: Integer.parseInt(req.getParameter("page"));
            int  pagesize = req.getParameter("row") ==null? 10: Integer.parseInt(req.getParameter("row"));
            String bname = req.getParameter("bname");
            PrintWriter out = resp.getWriter();
            HashMap<String, Object> map = new HashMap<>();
            String strwhere="";
            if (bname == null || bname.equals(""))
                strwhere= "";
            else
                strwhere =" where bname like '%"+bname+"%'";
            String sqlcount;
            sqlcount ="select count(*) from book" +strwhere;
            int total = Integer.parseInt(DBUtils.QueryScalar(sqlcount).toString());
            map.put("total", total);
            String sqllist = "select * from book "+strwhere+" limit "+(pageIndex-1)*pagesize+','+pagesize;
            List<Book> list = DBUtils.testDemoQueryBeanList(sqllist, Book.class);
            map.put("rows", list);
            out.write(JSON.toJSONString(map));
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
        private  void  Add (HttpServletRequest req, HttpServletResponse resp) throws IOException  {
            try {
                PrintWriter out = resp.getWriter();
                String bid = req.getParameter("bid");
                String bname =  new String(req.getParameter("bname").getBytes("iso-8859-1"),"utf-8");
                String bprice     =  new String(req.getParameter("bprice").getBytes("iso-8859-1"),"utf-8");
                String bimage =  new String(req.getParameter(" bimage").getBytes("iso-8859-1"),"utf-8");
                String bargainer =  new String(req.getParameter("bargainer").getBytes("iso-8859-1"),"utf-8");
                String isHot =  new String(req.getParameter("isHot").getBytes("iso-8859-1"),"utf-8");
                String bpdesc =  new String(req.getParameter("bpdesc").getBytes("iso-8859-1"),"utf-8");
                String cid =  new String(req.getParameter("cid").getBytes("iso-8859-1"),"utf-8");
                String sql = "insert into book(bid,bname,bprice,bimage,bargainer,isHot,bpdesc,cid) values(?,?,?,?,?,?,?,?)";
                if (DBUtils.testDemoUpdate(sql, bid, bname, bprice, bimage, bargainer,isHot,bpdesc,cid) > 0) {
                    out.write(JSON.toJSONString(new ResultData(String.valueOf(resp.getStatus()), "保存成功")));
                } else {
                    out.write(JSON.toJSONString(new ResultData("501", "保存失败")));
                }
            }
            catch (Exception e)
            {
                resp.getWriter().write(JSON.toJSONString(new ResultData("501", "数据有误无法保存")));
            }
        }
        private void  Exists(HttpServletRequest req, HttpServletResponse resp){
            try {
                PrintWriter out = resp.getWriter();
                String bid = req.getParameter("bid");
                String sql = "select count(*) from book where bid = ?";
                int count = Integer.parseInt(DBUtils.QueryScalar(sql,bid).toString());

                if (count ==1){
                    out.write("false");
                }
                else {
                    out.write("true");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        private  void  Delete(HttpServletRequest req, HttpServletResponse resp){
            try {
                PrintWriter out = resp.getWriter();
                String bid = req.getParameter("bid");
                String sql = "delete from book where bid =?";
                if (DBUtils.testDemoUpdate(sql,bid) >0){
                    out.write(JSON.toJSONString(new ResultData("200","删除成功")));
                }
                else
                    out.write(JSON.toJSONString(new ResultData("500","删除失败")));

            }catch (Exception e){
                e.printStackTrace();
            }
        }
        private  void  getOne(HttpServletRequest req, HttpServletResponse resp){

            resp.setContentType("text/html;charset=utf-8");
            resp.setCharacterEncoding("utf-8");
            try {
                PrintWriter out = resp.getWriter();
                String bid = req.getParameter("bid");
                String sql = "select * from book where bid= ?";
                Book book =   DBUtils.QueryBean(sql, Book.class,bid);
                ResultData rd= new ResultData();
                if (book != null){
                    rd.setCode(String.valueOf(resp.getStatus()));
                    rd.setMsg("获取成功");
                    rd.setData(book);
                    out.write(JSON.toJSONString(rd));
                }
                else {
                    rd.setCode("S01");
                    rd.setMsg("获取失败");
                    out.write(JSON.toJSONString(rd));
                }

            }catch (Exception e){
                e.printStackTrace();
            }
        }
        private  void  Update (HttpServletRequest req, HttpServletResponse resp) throws IOException  {

//        resp.setContentType("text/html;charset=utf-8");
            resp.setCharacterEncoding("utf-8");
            try {
                PrintWriter out = resp.getWriter();
                String bid = req.getParameter("bid");
                String bname =  new String(req.getParameter("bname").getBytes("iso-8859-1"),"utf-8");
                String bprice     =  new String(req.getParameter("bprice").getBytes("iso-8859-1"),"utf-8");
                String bimage =  new String(req.getParameter(" bimage").getBytes("iso-8859-1"),"utf-8");
                String bargainer =  new String(req.getParameter("bargainer").getBytes("iso-8859-1"),"utf-8");
                String isHot =  new String(req.getParameter("isHot").getBytes("iso-8859-1"),"utf-8");
                String bpdesc =  new String(req.getParameter("bpdesc").getBytes("iso-8859-1"),"utf-8");
                String cid =  new String(req.getParameter("cid").getBytes("iso-8859-1"),"utf-8");
                String sql = "update  ignore book set bname = ?,bprice = ?,bimage = ?,bargainer = ?,isHot = ?,bpdesc = ?, cid = ?,bid = ?";
                if (DBUtils.testDemoUpdate(sql,bname, bprice, bimage, bargainer ,isHot,bpdesc,cid,bid ) > 0) {
                    out.write(JSON.toJSONString(new ResultData(String.valueOf(resp.getStatus()), "保存成功")));
                } else {
                    out.write(JSON.toJSONString(new ResultData("501", "保存失败")));
                }
            }
            catch (Exception e)
            {
                resp.getWriter().write(JSON.toJSONString(new ResultData("501", "数据有误无法保存")));
            }
        }
    private  void  update (HttpServletRequest req, HttpServletResponse resp) throws IOException  {
        String bid = req.getParameter("bid");
        String bname =  new String(req.getParameter("bname").getBytes("iso-8859-1"),"utf-8");
        String bprice     =  new String(req.getParameter("bprice").getBytes("iso-8859-1"),"utf-8");
        String bimage = req.getParameter("bimage");
        String bargainer =  new String(req.getParameter("bargainer").getBytes("iso-8859-1"),"utf-8");
        String isHot =  new String(req.getParameter("isHot").getBytes("iso-8859-1"),"utf-8");
        String bpdesc =  new String(req.getParameter("bpdesc").getBytes("iso-8859-1"),"utf-8");
        String cid =  new String(req.getParameter("cid").getBytes("iso-8859-1"),"utf-8");
        String url = "jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF8&useSSL=true&serverTimezone=UTC";
        String dbusername = "root";
        String dbpassword = "123456";
        try {PrintWriter out = resp.getWriter();
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection connection = DriverManager.getConnection(url, dbusername, dbpassword);
            String sql ="update ignore book set bid=?, bname=?,  bprice=? , bimage=? , bargainer=?, isHot=?, bpdesc=?, cid=?   ";
            System.out.println("加入成功");
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,bid);
            ps.setString(2,bname);
            ps.setString(3,bprice);
            ps.setString(4,bimage);
            ps.setString(5,bargainer);
            ps.setString(6,isHot);
            ps.setString(7,bpdesc);
            ps.setString(8,cid);

            ResultData rd = new ResultData();
            if (ps.executeUpdate() >0){

                rd.setCode("200");
                rd.setMsg("修改成功");

//                resp.sendRedirect("index.jsp");
            }
            else {

                rd.setCode("501");
                rd.setMsg("修改失败");

//                resp.sendRedirect("login.jsp");
                //4.执行SQL的对象
            }
            out.write(JSON.toJSONString(rd));
        } catch (Exception e) {

            System.out.println(e.getMessage());
        }
    }
    private void  Reg(HttpServletRequest req, HttpServletResponse resp)throws IOException {
        String bid = req.getParameter("bid");
        String bname =  new String(req.getParameter("bname").getBytes("iso-8859-1"),"utf-8");
        String bprice     =  new String(req.getParameter("bprice").getBytes("iso-8859-1"),"utf-8");
        String bimage =  req.getParameter("bimage");
        String bargainer =  new String(req.getParameter("bargainer").getBytes("iso-8859-1"),"utf-8");
        String isHot =  new String(req.getParameter("isHot").getBytes("iso-8859-1"),"utf-8");
        String bpdesc =  new String(req.getParameter("bpdesc").getBytes("iso-8859-1"),"utf-8");
        String cid =  new String(req.getParameter("cid").getBytes("iso-8859-1"),"utf-8");
        String url = "jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF8&useSSL=true&serverTimezone=UTC";
        String dbusername = "root";
        String dbpassword = "123456";
        //1.加载驱动
        try {PrintWriter out = resp.getWriter();
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection connection = DriverManager.getConnection(url, dbusername, dbpassword);
            String sql ="insert into book(bid, bname, bprice, bimage,bargainer,isHot,bpdesc,cid) values (?,?,?,?,?,?,?,?)";
            PreparedStatement pst = connection.prepareStatement(sql);
            pst.setString(1,bid);
            pst.setString(2,bname);
            pst.setString(3,bprice);
            pst.setString(4,bimage);
            pst.setString(5,bargainer);
            pst.setString(6,isHot);
            pst.setString(7,bpdesc);
            pst.setString(8,cid);
            ResultData rd =new ResultData();
            if (pst.executeUpdate() >0){
                rd.setCode("200");
                rd.setMsg("成功");
            }
            else {  rd.setCode("501");
                rd.setMsg("失败");
            }
            out.write(JSON.toJSONString(rd));
        } catch (Exception e) {

            System.out.println(e.getMessage());
        }
    }
    }

